﻿using ERPWinFormWork.Test.Test.Dtos;
using ERPWinFormWork.Test.TestCode;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERPWinFormWork.Test
{
    public partial class SupplierMaterial_Table : Form
    {
        private ApiClient _apiClient;
        private readonly Action<Material_TableDtos> _onSelected;
        private readonly int _supplierId;

        public SupplierMaterial_Table(int supplierId, Action<Material_TableDtos> onSelected = null)
        {
            InitializeComponent();
            _apiClient = new ApiClient(TestAPI.TestApiBaseUrl);
            _supplierId = supplierId;
            _onSelected = onSelected;

            // 配置表格
            ConfigureDataGridView();

            LoadUnit();
            LoadType();
            Loadproperties();

            // 首次查询
            SearchAsync();
        }

        /// <summary>
        /// 配置数据表格
        /// </summary>
        private void ConfigureDataGridView()
        {
            if (dgvsuppliermater != null)
            {
                dgvsuppliermater.AllowUserToAddRows = false;
                dgvsuppliermater.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
                dgvsuppliermater.MultiSelect = true;

                // 绑定数据绑定完成事件
                dgvsuppliermater.DataBindingComplete += Dgvsuppliermater_DataBindingComplete;

                // 表头点击支持全选/取消
                dgvsuppliermater.ColumnHeaderMouseClick += Dgvsuppliermater_ColumnHeaderMouseClick;
            }
        }

        // 加载单位下拉框数据
        private async Task LoadUnit()
        {
            // 示例：加载下拉框
            var unitResponse = await _apiClient.GetAsync<TestApiResult<List<UnitModelDtos>>>(
                endpoint: "api/Read/GetUnitModel");

            if (unitResponse != null && unitResponse.code == 200)
            {
                // 清空并添加默认项
                cbounit_Id.Items.Clear();
                cbounit_Id.DisplayMember = "unitName"; // 显示名称
                cbounit_Id.ValueMember = "id";                 // 实际值存 ID
                cbounit_Id.DataSource = unitResponse.data;
                cbounit_Id.SelectedItem = null;
            }
        }

        // 加载物料类型下拉框数据
        private async Task LoadType()
        {
            // 示例：加载下拉框
            var materResponse = await _apiClient.GetAsync<TestApiResult<List<Material_TypeDtos>>>(
                endpoint: "api/Read/GetMaterial_TypeDtos");

            if (materResponse != null && materResponse.code == 200)
            {
                // 清空并添加默认项
                cbotype_Id.Items.Clear();
                cbotype_Id.DisplayMember = "typeName"; // 显示名称
                cbotype_Id.ValueMember = "id";                 // 实际值存 ID
                cbotype_Id.DataSource = materResponse.data;
                cbotype_Id.SelectedItem = null;
            }
        }

        // 加载物料属性下拉框数据
        private async Task Loadproperties()
        {
            // 示例：加载下拉框
            var propertiesResponse = await _apiClient.GetAsync<TestApiResult<List<Material_PropertiesDtos>>>(
                endpoint: "api/Read/GetMaterial_PropertiesDtos");

            if (propertiesResponse != null && propertiesResponse.code == 200)
            {
                // 清空并添加默认项
                cboproperties_Id.Items.Clear();
                cboproperties_Id.DisplayMember = "propertiesName"; // 显示名称
                cboproperties_Id.ValueMember = "id";                 // 实际值存 ID
                cboproperties_Id.DataSource = propertiesResponse.data;
                cboproperties_Id.SelectedItem = null;
            }
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSearch_Click(object sender, EventArgs e)
        {
            var queryParams = new Dictionary<string, string>();
            if (cbounit_Id.SelectedValue != null)
            {
                queryParams["unit_Id"] = ((int)cbounit_Id.SelectedValue).ToString();
            }

            if (cbotype_Id.SelectedValue != null)
            {
                queryParams["type_Id"] = ((int)cbotype_Id.SelectedValue).ToString();
            }
            if (cboproperties_Id.SelectedValue != null)
            {
                queryParams["properties_Id"] = ((int)cboproperties_Id.SelectedValue).ToString();
            }
            SearchAsync(queryParams);
        }

        /// <summary>
        /// 重置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnReset_Click(object sender, EventArgs e)
        {
            textmaterialNameOrNumber.Text = string.Empty;
            cbounit_Id.Text = string.Empty;
            cbotype_Id.Text = string.Empty;
            cboproperties_Id.Text = string.Empty;
            SearchAsync();
        }

        // 不再提供每行“选择”按钮或双击立即返回；改为勾选并点页面“选择”按钮

        /// <summary>
        /// 数据绑定完成事件
        /// </summary>
        private void Dgvsuppliermater_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            // 确保有复选框列
            EnsureCheckBoxColumn();
        }

        /// <summary>
        /// 确保复选框列存在
        /// </summary>
        private void EnsureCheckBoxColumn()
        {
            if (!dgvsuppliermater.Columns.Contains("colCheckBox"))
            {
                var checkCol = new DataGridViewCheckBoxColumn
                {
                    Name = "colCheckBox",
                    HeaderText = "选择",
                    Width = 60
                };
                dgvsuppliermater.Columns.Add(checkCol);
                checkCol.DisplayIndex = 0;
            }
        }

        // 表头点击：切换全选/取消全选
        private void Dgvsuppliermater_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            var grid = sender as DataGridView;
            if (grid == null || e.ColumnIndex < 0) return;
            if (grid.Columns[e.ColumnIndex].Name != "colCheckBox") return;

            bool allChecked = true;
            foreach (DataGridViewRow row in grid.Rows)
            {
                if (row.Cells["colCheckBox"].Value == null || !(bool)row.Cells["colCheckBox"].Value)
                {
                    allChecked = false;
                    break;
                }
            }
            foreach (DataGridViewRow row in grid.Rows)
            {
                row.Cells["colCheckBox"].Value = !allChecked;
            }
        }

        /// <summary>
        /// 查询供应商物料信息
        /// </summary>
        private async Task SearchAsync(Dictionary<string, string> customParams = null)
        {
            var parameters = new Dictionary<string, string>
            {
                { "supplierId", _supplierId.ToString() }
            };

            if (!string.IsNullOrWhiteSpace(textmaterialNameOrNumber.Text))
            {
                parameters["materialNumberOrName"] = textmaterialNameOrNumber.Text.Trim();
            }

            // 合并自定义参数（查询条件）
            if (customParams != null)
            {
                foreach (var kv in customParams)
                {
                    parameters[kv.Key] = kv.Value;
                }
            }

            var resp = await _apiClient.GetAsync<TestApiResult<List<Material_TableDtos>>>(
                endpoint: "api/Read/GetMaterial_Table",
                parameters: parameters);

            if (resp != null && resp.code == 200)
            {
                dgvsuppliermater.AutoGenerateColumns = true;
                dgvsuppliermater.DataSource = resp.data ?? resp.pageDatas;
            }
        }
        /// <summary>
        /// 选择：将勾选的物料回填到上一个页面
        /// </summary>
        private void btnChange_Click(object sender, EventArgs e)
        {
            if (dgvsuppliermater == null || dgvsuppliermater.Rows.Count == 0)
            {
                MessageBox.Show("没有可选择的数据", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            var selected = new List<Material_TableDtos>();
            foreach (DataGridViewRow row in dgvsuppliermater.Rows)
            {
                bool isChecked = false;
                if (row.Cells["colCheckBox"] != null && row.Cells["colCheckBox"].Value != null)
                {
                    bool.TryParse(row.Cells["colCheckBox"].Value.ToString(), out isChecked);
                }
                if (!isChecked) continue;
                if (row.DataBoundItem is Material_TableDtos item)
                {
                    selected.Add(item);
                }
            }

            if (selected.Count == 0)
            {
                MessageBox.Show("请先勾选需要添加的物料", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            if (_onSelected != null)
            {
                foreach (var item in selected)
                {
                    _onSelected(item);
                }
            }

            this.DialogResult = DialogResult.OK;
            this.Close();
        }
    }
}
